"""
安全评价模块管理后台配置

此模块配置了Django管理后台的安全评价相关功能，包括：
- SafetyEvaluation模型的管理界面
- 字段显示和筛选配置
- 搜索和批量操作功能
- 数据导出和统计功能

作者：矿山安全评价系统开发团队
版本：1.0.0
更新时间：2025-10-12
"""

from django.contrib import admin
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from .models import SafetyEvaluation


@admin.register(SafetyEvaluation)
class SafetyEvaluationAdmin(admin.ModelAdmin):
    """
    安全评价模型管理配置
    """
    
    # 列表页显示字段
    list_display = [
        'evaluation_id',
        'mine_name', 
        'evaluator_name',
        'evaluation_date',
        'get_region_display',
        'get_evaluation_category_display',
        'get_comprehensive_score',
        'get_safety_level',
        'created_at',
    ]
    
    # 列表页筛选器
    list_filter = [
        'evaluation_category',
        'region',
        'evaluation_date',
        'created_at',
        'updated_at',
    ]
    
    # 搜索字段
    search_fields = [
        'evaluation_id',
        'mine_name',
        'evaluator_name',
    ]
    
    # 排序字段
    ordering = ['-created_at']
    
    # 每页显示数量
    list_per_page = 20
    
    # 详情页字段分组
    fieldsets = (
        ('基本信息', {
            'fields': (
                'evaluation_id',
                'evaluation_date', 
                'evaluator_name',
                'mine_name',
                'region',
                'evaluation_category',
            ),
            'classes': ('wide',),
        }),
        ('矿山基本信息', {
            'fields': (
                'affiliated_enterprise',
                'production_capacity',
                'service_life',
                'development_methods',
                'transport_method',
            ),
            'classes': ('wide',),
        }),
        ('生产系统信息', {
            'fields': (
                'current_production_system',
                'production_systems',
            ),
            'classes': ('wide',),
        }),
        ('人员因素指标', {
            'fields': (
                'worker_safety_awareness',
                'management_capability',
            ),
            'classes': ('wide',),
        }),
        ('设备完好率指标', {
            'fields': (
                'mining_equipment_integrity',
                'ventilation_equipment_integrity',
                'gas_monitoring_equipment_integrity',
                'fire_prevention_equipment_integrity',
                'drainage_equipment_integrity',
                'hoisting_equipment_integrity',
                'power_system_integrity',
            ),
            'classes': ('wide',),
        }),
        ('环境与工艺指标', {
            'fields': (
                'air_supply_demand_ratio',
                'roof_management_difficulty',
                'coal_spontaneous_combustion_tendency',
            ),
            'classes': ('wide',),
        }),
        ('管理制度指标', {
            'fields': (
                'safety_management_implementation',
                'emergency_response_completeness',
                'safety_inspection_implementation',
            ),
            'classes': ('wide',),
        }),
        ('元数据', {
            'fields': (
                'created_at',
                'updated_at',
            ),
            'classes': ('collapse',),
        }),
    )
    
    # 只读字段
    readonly_fields = [
        'evaluation_id',
        'created_at', 
        'updated_at',
    ]
    
    # 批量操作
    actions = [
        'calculate_batch_scores',
        'export_selected_evaluations',
    ]
    
    def get_comprehensive_score(self, obj):
        """显示综合得分"""
        try:
            score = obj.calculate_comprehensive_score()
            return format_html(
                '<span style="font-weight: bold; color: {};">{:.2%}</span>',
                '#28a745' if score >= 0.8 else '#ffc107' if score >= 0.6 else '#dc3545',
                score
            )
        except Exception:
            return '计算错误'
    get_comprehensive_score.short_description = '综合得分'
    get_comprehensive_score.admin_order_field = 'created_at'
    
    def get_safety_level(self, obj):
        """显示安全等级"""
        try:
            level = obj.get_safety_level()
            color_map = {
                'A级(优秀)': '#28a745',
                'B级(良好)': '#17a2b8', 
                'C级(一般)': '#ffc107',
                'D级(较差)': '#fd7e14',
            }
            color = color_map.get(level, '#6c757d')
            return format_html(
                '<span style="padding: 3px 8px; border-radius: 3px; color: white; background-color: {}; font-size: 12px;">{}</span>',
                color,
                level
            )
        except Exception:
            return '等级错误'
    get_safety_level.short_description = '安全等级'
    
    def calculate_batch_scores(self, request, queryset):
        """批量计算评价得分"""
        updated_count = 0
        for evaluation in queryset:
            try:
                # 触发得分重新计算（通过保存操作）
                evaluation.save()
                updated_count += 1
            except Exception:
                continue
        
        self.message_user(
            request,
            f'成功重新计算了 {updated_count} 条评价记录的得分。'
        )
    calculate_batch_scores.short_description = '重新计算选中项的综合得分'
    
    def export_selected_evaluations(self, request, queryset):
        """导出选中的评价数据"""
        # 这里可以实现CSV或Excel导出功能
        evaluation_ids = list(queryset.values_list('id', flat=True))
        self.message_user(
            request,
            f'已选择 {len(evaluation_ids)} 条记录进行导出。（导出功能开发中）'
        )
    export_selected_evaluations.short_description = '导出选中的评价数据'
    
    def has_delete_permission(self, request, obj=None):
        """控制删除权限"""
        # 只有超级管理员可以删除评价记录
        return request.user.is_superuser
    
    def get_readonly_fields(self, request, obj=None):
        """动态设置只读字段"""
        readonly_fields = list(self.readonly_fields)
        
        # 如果是编辑现有对象，评价编号不可修改
        if obj:
            readonly_fields.append('evaluation_id')
            
        return readonly_fields
